// src/composables/useRegister.js
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { useToast } from './useToast';
import { useApi } from './useApi';

export function useRegister() {
    const router = useRouter();
    const { success, error, warning } = useToast();

    const username = ref('');
    const phone = ref('');
    const email = ref('');
    const password = ref('');
    const confirmPassword = ref('');

    const { loading, result, fetchData } = useApi({
        url: '/auth/register',
        method: 'post',
        manual: true
    });

    // 提交注册
    async function register() {
        // 检查2次密码是否一致
        if (password.value !== confirmPassword.value) {
            warning('两次输入的密码不一致');
            return;
        }

        try {
            await fetchData({
                data: {
                    username: username.value,
                    phone: phone.value,
                    email: email.value,
                    password: password.value
                }
            });

            const res = result.value;
            if (res?.code === 0) {
                success('注册成功，请登录~');
                router.push('/login');
            } else {
                error(res?.msg);
            }
        } catch (err) {
            console.log(err);
        }
    }

    return {
        username, // 用户名双向绑定
        phone, // 手机号双向绑定
        email, // 邮箱双向绑定
        password, // 密码双向绑定
        confirmPassword,
        loading, // 请求loading状态
        register // 触发登录函数
    };
}
